//
//  JHDataStorageFactory.m
//  MiniWeChat
//
//  Created by ByteDance on 2025/6/25.
//
#import "JHDataStorageFactory.h"

@implementation JHDataStorageFactory

+ (instancetype)sharedFactory {
    static JHDataStorageFactory *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (id<JHDataStorage>)createStorageWithType:(NSString *)type configuration:(NSDictionary *)configuration error:(NSError **)error {
    // 从配置文件读取类名
    NSDictionary *providers = [self registeredProviders];
    NSString *className = providers[type];
    
    if (!className) {
        if (error) {
            *error = [NSError errorWithDomain:@"JHDataStorageFactoryError" code:1000 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"No provider found for type: %@", type]}];
        }
        return nil;
    }
    
    // 使用运行时创建实例
    Class providerClass = NSClassFromString(className);
    if (![providerClass conformsToProtocol:@protocol(JHStorageProvider)]) {
        if (error) {
            *error = [NSError errorWithDomain:@"JHDataStorageFactoryError" code:1002 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Class %@ does not conform to JHStorageProvider protocol", className]}];
        }
        return nil;
    }
    
    return [[providerClass alloc] initWithConfiguration:configuration];
}

- (NSDictionary *)registeredProviders {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"StorageProviders" ofType:@"plist"];
    return [NSDictionary dictionaryWithContentsOfFile:path];
}

@end
